package assist;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author lyx
 * @Date 2021/6/25 11:55
 * 辅助类-信号量
 * 并发与限流中经常使用
 *例子:模拟6辆车,抢占2个停车位
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        //线程数量:停车位
        Semaphore semaphore = new Semaphore(2);
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();//********获得
                    System.out.println("第"+Thread.currentThread().getName()+"号车,抢到车位!");
                    TimeUnit.SECONDS.sleep(5);
                    System.out.println("第"+Thread.currentThread().getName()+"停车完毕,离开车位!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();//*********释放
                }
            },String.valueOf(i)).start();//String.valueOf(i) 获取名字, 把for循环的i = 当前线程名字
        }
    }
}
